/**
 * @Author 天下无敌
 * @Date 
 * @AIDE AIDE+ 
 */
package com.ecs.core.system;


import com.artemis.ComponentMapper;
import com.artemis.annotations.All;
import com.artemis.systems.IteratingSystem;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
//import com.ecs.core.debug.Debug;
import com.ecs.core.components.attribute.Transform;
import com.ecs.core.components.attribute.MovementComp;

/**
 * 移动系统：处理实体移动和角度更新
 */
@All({Transform.class, MovementComp.class})
public class MovementSystem extends IteratingSystem {
	
	public static final String TAG = "MovementSystem";
    private ComponentMapper<Transform> mTransform;
    private ComponentMapper<MovementComp> mMovement;

    @Override
    protected void process(int entityId) {
        Transform transform = mTransform.get(entityId);
        MovementComp move = mMovement.get(entityId);

        // 1. 如果有速度输入，更新角度和速度
        if (!move.velocity.isZero()) {
            // 计算当前移动方向的角度（0度为正上方，顺时针增加）
            move.currentAngle = MathUtils.atan2(move.velocity.x, move.velocity.y) * MathUtils.radiansToDegrees;
			move.currentAngle = (move.currentAngle % 360 + 360) % 360; // 标准化
            // 应用加速度
            Vector2 direction = move.velocity.cpy().nor();
            move.velocity.add(
                direction.x * move.acceleration * world.getDelta(),
                direction.y * move.acceleration * world.getDelta()
            );

            // 限制最大速度
            float maxSpeed = move.moveSpeed;
            if (move.velocity.len() > maxSpeed) {
                move.velocity.nor().scl(maxSpeed);
            }
			
			//Debug.log(TAG,String.format("Entity %d is moving, with a speed of x %f y %f",entityId,move.velocity.x,move.velocity.y));
		}
        // 2. 无输入时应用减速度
        else if (move.deceleration > 0) {
            float reduction = move.deceleration * world.getDelta();
            float currentSpeed = move.velocity.len();
            if (currentSpeed > reduction) {
                move.velocity.setLength(currentSpeed - reduction);
            } else {
                move.velocity.setZero();
            }
        }

        // 3. 更新位置
        transform.pos.add(
            move.velocity.x * world.getDelta(),
            move.velocity.y * world.getDelta()
        );
    }
}
